package demo1;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2024-01-15
 * Time: 22:55
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(int[] elem) {
        this.elem = new int[10];
    }
    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    private void swap(int a, int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }

    /**
     * 向下调整建堆的时间复杂度：O(N)********重点记忆
     */
    public void createHeap() {
        for (int parent = (usedSize-2) / 2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }
    private void shiftDown(int parent, int len) {
        int child = 2*parent + 1;
        while (child < len) {
            if (child+1 < len && elem[child] < elem[child+1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }
    //如果用向上调整建堆，时间复杂度为O(N*logN)
    public void shiftUp(int child) {
        int parent = (child-1) / 2;
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                swap(parent,child);
                child = parent;
                parent = (child-1) / 2;
            }else {
                break;
            }
        }
    }
    //插入数据
    public void offer(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = val;
        shiftUp(usedSize-1);
    }
    //判满
    public boolean isFull() {
        return usedSize == elem.length;
    }
    //弹出数据
    public void pop() throws EmptyException {
        if (isEmpty()) {
            throw new EmptyException("堆为空");
        }
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }
    public int peek() throws EmptyException {
        if (isEmpty()) {
            throw new EmptyException("堆为空");
        }
        return elem[0];
    }

    /**
     * 堆排序
     * 空间复杂度：O(1)
     * 时间复杂度：O(N*longN)
     */
    public void heapSort() {
        int end = usedSize-1;
        while (end > 0) {
            swap(0,end);
            shiftDown(0,end);
            end--;
        }
    }
}
